package com.fengxu.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

// 服务器管道处理器
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    // 读取通道中的数据
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 读取客户端发送的StudentPOJO.student对象
        StudentPOJO.Student student = (StudentPOJO.Student) msg;
        System.out.println("服务器读取到: id ->"+student.getId() + "; name ->" + student.getName());
    }


    // 通道读取完毕事件
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        // 将数据写入缓冲区并flush
        ctx.writeAndFlush(Unpooled.copiedBuffer("Hello 客户端",CharsetUtil.UTF_8));
    }

    // 异常处理,一般是关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
